package com.miage.kangourou.server.dao.impl;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.miage.kangourou.client.beans.Enseignant;

public class EnseignantDao extends GenericDao<Enseignant> {

	public EnseignantDao(Connection connect) {
		super(connect);
	}

	public Enseignant findById(int id) throws SQLException {
		ResultSet result = connect.createStatement(
				ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)
				.executeQuery(
						"SELECT * FROM ENSEIGNANT WHERE ID_ENSEIGNANT = " + id);

		Enseignant enseignant;

		if (result.next()) {
			enseignant = new Enseignant(result.getInt("ID_ENSEIGNANT"), result
					.getString("CIVILITE"), result.getString("NOM"), result
					.getString("PRENOM"), result.getString("EMAIL"));
		} else {
			enseignant = new Enseignant();
		}

		result.close();

		return enseignant;
	}

	public List<Enseignant> findAll() throws SQLException {
		ResultSet result = connect.createStatement(
				ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)
				.executeQuery("SELECT * FROM ENSEIGNANT");

		List<Enseignant> all = new ArrayList<Enseignant>();
		while (result.next()) {
			all.add(new Enseignant(result.getInt("ID_ENSEIGNANT"), result
					.getString("CIVILITE"), result.getString("NOM"), result
					.getString("PRENOM"), result.getString("EMAIL")));
		}

		result.close();

		return all;
	}

	public void create(Enseignant enseignant) throws SQLException {
		if (enseignant instanceof Enseignant && !enseignant.equals(null)) {

			connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY).executeQuery(
							"INSERT INTO ENSEIGNANT (CIVILITE, NOM, PRENOM, EMAIL) VALUES ("
							+ "\"" + enseignant.getCivilite() + "\", " + "\""
							+ enseignant.getNom() + "\", " + "\""
							+ enseignant.getPrenom() + "\", " + "\""
							+ enseignant.getEmail() + "\")");
		}
	}

	public boolean alreadyExist(Enseignant enseignant) throws SQLException {
		boolean exist = false;

		if (enseignant instanceof Enseignant && !enseignant.equals(null)) {

			ResultSet result = connect.createStatement(
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY).executeQuery(
							"SELECT * FROM ENSEIGNANT WHERE ID_ENSEIGNANT = "
							+ enseignant.getId_enseignant());

			if (result.next()) {
				exist = true;
			}

			result.close();
		}

		return exist;
	}

	public boolean delete(int idEnseignant) {

		boolean deleted = true;

		try {
			connect.createStatement(
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY).executeQuery(
							"DELETE FROM ENSEIGNANT WHERE ID_ENSEIGNANT = "
							+ idEnseignant);
		} catch (SQLException e) {
			e.printStackTrace();
			deleted = false;
		}



		return deleted;
	}
}